﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims;
using 第二课堂评审系统.Models;
using Microsoft.Extensions.Options;

namespace 第二课堂评审系统.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class StudentController : ControllerBase
    {
        private readonly _MyDbContext Db;
        private readonly IOptionsSnapshot<JWTSettings> jwtSettingsOpt;
        public StudentController(_MyDbContext db, IOptionsSnapshot<JWTSettings> jwtSettingsOpt)
        {
            Db = db;
            this.jwtSettingsOpt = jwtSettingsOpt;
        }

        #region 获取我的小组信息
        [HttpGet]
        public ActionResult getGroupInfo()
        {
            using _MyDbContext Context=new _MyDbContext();
            //获取当前登录用户
            int stuNum = Convert.ToInt32(this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value);
            var user = Context.Users.Where(o => o.StuNum == stuNum).FirstOrDefault()!;

            //获取小组
            Partnar partnar = Context.Partnars.Include(o => o.members)!.ThenInclude(o=>o.Roles).Include(o => o.guideTeacher).Where(o => o.members != null ? o.members.Contains(user) : false).ToList().FirstOrDefault()!;


            if (partnar != null)
            {
                List<object> list = new List<object>();
                //处理小组的成员
                if (partnar.members != null)
                {
                    foreach (User m in partnar.members)
                    {
                        list.Add(new
                        {
                            Sno = m.StuNum,
                            Sname = m.Name,
                            Sphone = m.telPhone,
                            Scollege = m.college,
                            Semail = m.email,
                            Sidentity =m.Roles==null?null: m.Roles![0].Name,
                        });
                    }
                }
                var js = new
                {
                    haveGroup = true,
                    inviteCode = partnar.inviteNum,
                    groupName = partnar.Name,
                    groupAvatarUrl = "/PartnarAvatar/"+partnar.avatorUrl,
                    leaderTeacher = partnar.guideTeacher==null?null:partnar.guideTeacher!.Name,
                    groupType = partnar.searchDirection, 
                    itemType = partnar.projectDirection==null?null:partnar.projectDirection!.Split(','),
                    innovationType = partnar.innovateDirection,
                    notes = partnar.Description,
                    members = list,
                };
                return new JsonResult(js);
            }
            else
            {
                var js = new
                {
                    haveGroup = false,
                    inviteCode = 0,
                    groupName = "",
                    groupAvatarUrl = "",
                    leaderTeacher = "",
                    groupType = "",
                    itemType = "",
                    innovationType = "",
                    notes = "",
                    members = "",
                };
                return new JsonResult(js);
            }

        }
        #endregion



        #region 修改小组信息
        public record PartnarInfo(string groupName, string leaderTeacher, string? groupType, List<string>? itemType, string? innovationType, string? notes,int? inviteCode);
        [HttpPost]

        public ActionResult updateGroupInfo(PartnarInfo partnarInfo)
        {
            using _MyDbContext Context = new _MyDbContext();
            //获取当前用户
            int stuNum = Convert.ToInt32(this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value);
            var user = Context.Users.Include(o=>o.partnar).ThenInclude(o=>o!.guideTeacher).Where(o => o.StuNum == stuNum).FirstOrDefault()!;

            //获取小组
            Partnar partnar = Context.Partnars.Include(o=>o.guideTeacher).Where(o => o.members != null ? o.members.Contains(user) : false).FirstOrDefault()!;
            //查看小组名是否冲突
            Partnar partnar2 = Context.Partnars.Where(o => o.Name == partnarInfo.groupName&&o.Name!=user.partnar!.Name).FirstOrDefault()!;
            if (partnar2 != null)
            {
                return BadRequest("修改失败，小组名‘" + partnarInfo.groupName + "’已被使用");
            }
            //获取指导老师
            User guideTeacher;
            if(user.partnar!.guideTeacher==null||user.partnar!.guideTeacher!.Name!=partnarInfo.leaderTeacher)
            try
            {
                guideTeacher = Context.Users.Where(o => o.StuNum == Convert.ToInt32(partnarInfo.leaderTeacher)).FirstOrDefault()!;
                if (guideTeacher == null)
                {
                    return BadRequest("修改失败，指导老师不存在");
                }
                partnar.guideTeacher = guideTeacher;
            }
            catch
            {
                return BadRequest("修改失败，指导老师不存在");
            }
            //修改信息
            partnar.Name = partnarInfo.groupName;
            partnar.searchDirection = partnarInfo.groupType;
            partnar.projectDirection =  string.Join(",",partnarInfo.itemType!);
            partnar.innovateDirection = partnarInfo.innovationType;
            partnar.Description = partnarInfo.notes;

            //保存修改
            Context.SaveChangesAsync();
            return Ok("修改成功");
        }
        #endregion



        #region 删除成员
        [HttpPost]
        public ActionResult deleteMember([FromBody]string Sno)
        {
            using _MyDbContext Context = new _MyDbContext();
            //获取当前用户
            int stuNum = Convert.ToInt32(this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value);
            var user = Context.Users.Where(o => o.StuNum == stuNum).FirstOrDefault()!;

            //删除的成员不能是组长
            if (Convert.ToInt32(Sno) == user.StuNum)
            {
                return BadRequest("删除失败，组长不能被删除");
            }

            //获取小组组员
            List<User> members = Context.Partnars.Include(o => o.members).Where(o => o.members==null?false:o.members.Contains(user)).FirstOrDefault()!.members!;

            //获取要删除的组员
            User deleteUser = Context.Users.Where(o => o.StuNum == Convert.ToInt32(Sno)).FirstOrDefault()!;

            if (deleteUser == null)
            {
                return BadRequest("删除失败，没有该成员");
            }
            else
            {
                members.Remove(deleteUser);
                Context.SaveChangesAsync();
                return Ok("删除成功");
            }
        }
        #endregion



        #region 邀请码加入小组
        [HttpPost]
        public ActionResult addGroup([FromBody]string inviteCode)
        {
            using _MyDbContext Context = new _MyDbContext();
            //获取邀请码的小组
            Partnar partnar;
            try
            {
                partnar = Context.Partnars.Include(o=>o.members).Where(o => o.inviteNum == Convert.ToInt32(inviteCode)).FirstOrDefault()!;
            }
            catch
            {
                return BadRequest("加入失败，邀请码无效");
            }
            
            if(partnar != null) 
            {
                //获取当前用户
                int stuNum = Convert.ToInt32(this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value);
                var user = Context.Users.Include(o=>o.Roles).Where(o => o.StuNum == stuNum).FirstOrDefault()!;
                //添加成员
                Role role = new Role();
                role.Name = "S0";
                if (user.Roles == null || user.Roles.Count == 0)
                {
                    user.Roles = new List<Role>();
                    user.Roles.Add(role);
                }
                else
                {
                    if (user.Roles[0].Name != "S0")
                    {
                        return BadRequest("加入失败，只有学生才能加入小组");
                    }
                    user.Roles![0].Name="S0";
                }
                partnar.members!.Add(user);
                Context.SaveChangesAsync();
                return Ok("小组加入成功");
            }
            else
            {
                return BadRequest("加入失败，邀请码无效");
            }

        }
        #endregion




        #region 获得所有老师
        [HttpGet]
        public ActionResult getTeachers()
        {
            using _MyDbContext dbContext= new _MyDbContext();
            List<User> users = dbContext.Users.Include(u => u.Roles).ToList();
            users=users.Where(u => u.Roles[0].Name == "T0" || u.Roles[0].Name=="T1").ToList();
            if(users.Count == 0)
            {
                return BadRequest("还没有老师");
            }
            var js = users.Select(u => new {sno=u.StuNum,name=u.Name}).ToList();
            return Ok(js);
        }
        #endregion



        #region 创建小组
        [HttpPost]
        public ActionResult createGroup(IFormFile avatarFile, string? groupName, string? leaderTeacher,string? counsellor, string? groupType,string itemType, string? innovationType, string? notes)
        {
            using (_MyDbContext Context = new _MyDbContext())
            {
                Partnar partnar = new Partnar();
                List<User> members = new List<User>();

                //获取当前登录用户
                int StuNum = Convert.ToInt32(this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value);
                var user = Context.Users.Include(o => o.Roles).Where(o => o.StuNum == StuNum).FirstOrDefault()!;
                //查询小组名是否重复
                Partnar partnar2 = Context.Partnars.Where(o => o.Name == groupName).FirstOrDefault()!;
                if (partnar2 != null)
                {
                    return BadRequest("创建失败，小组名‘" + groupName + "’已被使用");
                }
                //获取指导老师
                User guideTeacher;
                try
                {
                    guideTeacher = Context.Users.Where(o => o.StuNum == Convert.ToInt32(leaderTeacher)).FirstOrDefault()!;
                    if (guideTeacher == null)
                    {
                        return BadRequest("创建失败，指导老师不存在");
                    }
                }
                catch
                {
                    return BadRequest("创建失败，指导老师不存在");
                }
                //设置当前用户角色为组长
                Role role = new Role();
                role.Name = "S1";
                if (user.Roles == null || user.Roles.Count == 0)
                {
                    user.Roles = new List<Role>();
                    user.Roles.Add(role);
                }
                else
                {
                    user.Roles![0].Name="S1";
                }

                //成员表添加当前用户
                partnar.members = members;
                partnar.members!.Add(user);
                //绑定项目
                partnar.project = null;
                Project project = new Project();
                project.projectState = 1;
                partnar.project = project;
                project.Partnar = partnar;
                //绑定决赛成绩
                partnar.MyFinal = null;
                //绑定初赛成绩
                partnar.MyPreliminary = null;
                //随机生成邀请码
                while (true)
                {
                    Random random = new Random(Guid.NewGuid().GetHashCode());
                    int num = random.Next(100000, 999999);
                    Partnar partnar3 = Context.Partnars.Where(o => o.inviteNum == num).FirstOrDefault()!;
                    if (partnar3 == null)
                    {
                        partnar.inviteNum = num;
                        break;
                    }
                }

                //绑定参数
                //上传头像
                var path = string.Format("{0}_{1}", DateTime.Now.Ticks, avatarFile.FileName);
                var path1 = Path.Combine("wwwroot\\PartnarAvatar", path);
                var path2 = Path.Combine(Directory.GetCurrentDirectory(), path1);
                using (var stream = new FileStream(path2, FileMode.Create))
                {
                    avatarFile.CopyTo(stream);
                }
                partnar.avatorUrl = path;
                partnar.Name = groupName;
                partnar.guideTeacher = guideTeacher;
                partnar.searchDirection = groupType;
                partnar.counsellor = counsellor;
                partnar.projectDirection = itemType;
                partnar.innovateDirection = innovationType;
                partnar.Description = notes;
                //保存信息
                Context.Partnars.Add(partnar);
                Context.Projects.Add(project);
                Context.SaveChanges();
                return Ok(partnar.Name);
            }
        }
        #endregion



        public record projectInfo(string programName,string programType,string programIntroduce);
        [HttpPost]//创建项目
        public ActionResult createProgram([FromBody] projectInfo info)
        {
                var UID = this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value;
                User user = Db.Users.Where(u => u.StuNum.ToString() == UID).Include(u => u.partnar).ThenInclude(p=>p.project).ThenInclude(u=>u.OperationTimes).ToList().SingleOrDefault()!;
                
                if(user.partnar!.project!.Name==null)//为空创建项目
                {
                    user.partnar!.project!.Name = info.programName;
                    user.partnar!.project!.Description = info.programIntroduce;
                    user.partnar!.project!.Direction = info.programType;
                    user.partnar!.project!.projectState = 2;//项目审核

                    List<OperationTime> operationTimes = new List<OperationTime>();
                    OperationTime operation = new OperationTime();//添加操作时间
                    operation.Time = DateTime.Now;

                    operation.worker = user.Name;
                    operation.Project = user.partnar!.project!;
                    operationTimes.Add(operation);
                    user.partnar!.project!.OperationTimes = operationTimes;

                    Db.OperationTimes.Add(operation);
                }
                else 
                    {
                        user.partnar!.project!.Name = info.programName;
                        user.partnar!.project!.Description = info.programIntroduce;
                        user.partnar!.project!.Direction = info.programType;
                        user.partnar!.project!.projectState = 2;//项目审核
                        user.partnar!.project!.isPassed = null;
                        user.partnar!.project!.OperationTimes!.Clear();
                        OperationTime operation = new OperationTime();//添加操作时间
                        operation.Time = DateTime.Now;
                        operation.worker = user.Name;
                        user.partnar!.project!.OperationTimes!.Add(operation);
                     }
                
                
                Db.SaveChanges();
         
            return Ok("项目创建成功");

        }
        [HttpGet]//获取日志
        public ActionResult getUploadLog()
        {
            var UID = this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value;
            User user = Db.Users.Where(u => u.StuNum.ToString() == UID).Include(u => u.partnar).ThenInclude(p=>p.project).ThenInclude(p=>p.OperationTimes).ToList().SingleOrDefault()!;
            List<OperationTime> operationTimes = user.partnar!.project!.OperationTimes!;
            var js = new {programLogs= operationTimes.OrderBy(o => o.Time).Select(o => new { time=o.Time.ToString(), worker=o.worker }) };//排序，映射，返回
            return new JsonResult(js);
        }
        [HttpPost]//上传项目源文件
        public ActionResult uploadFile(IFormFile file)
        {
            //获取token中的值
            var UID = this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value;
            User user = Db.Users.Where(u => u.StuNum.ToString() == UID).Include(u => u.partnar).ThenInclude(p => p.project).ThenInclude(p =>p.OperationTimes).ToList().SingleOrDefault()!;
            if (file != null && file.Length != 0)
            {
                //判断并删除旧文件
                if (user.partnar!.project!.FileUrl != null)
                {

                    var pt = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\ProjectFile", user.partnar!.project!.FileUrl!);
                    if (System.IO.File.Exists(pt))
                    {
          
                        System.IO.File.Delete(pt);
                    }
                }
                var path = string.Format("{0}_{1}", DateTime.Now.Ticks, file.FileName);
                var path1 = Path.Combine("wwwroot\\ProjectFile", path);
                var path2 = Path.Combine(Directory.GetCurrentDirectory(), path1);

                using (var stream = new FileStream(path2, FileMode.Create))
                {
                    file.CopyTo(stream);
                }
                user.partnar!.project!.FileUrl = path;
                user.partnar.project.projectState = 3;//下一阶段初赛
                OperationTime operationTime = new OperationTime();
                operationTime.Time = DateTime.Now;
                operationTime.worker = user.Name;
                user.partnar.project.OperationTimes!.Add(operationTime);
                Db.SaveChanges();
                var js = new
                {
                    log = new
                    {
                        time = operationTime.Time,
                        worker = user.Name
                    }
                };
                return new JsonResult(js);
            }
            else return BadRequest("文件不能为空");
        }
        [HttpPost]//初赛签到
        public ActionResult oSignIn()
        {
            //获取token中的值
            var UID = this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value;
            User user = Db.Users.Where(u => u.StuNum.ToString() == UID).Include(u => u.partnar).ThenInclude(p => p.project).Include(p=>p.partnar).ThenInclude(p=>p.MyPreliminary).ThenInclude(p=>p.Partnars).ToList().SingleOrDefault()!;

            try
            {
                Partnar partnar = user.partnar!;
                user.partnar!.MyPreliminary!.Partnars!.Add(partnar);
                user.partnar.project!.projectState = 5;
                Db.SaveChanges();
            }
            catch
            {
                return BadRequest("签到失败");
            }
            return Ok("签到成功");
        }
        [HttpPost]//决赛签到
        public ActionResult fSignIn()
        {
            //获取token中的值
            var UID = this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value;
            User user = Db.Users.Where(u => u.StuNum.ToString() == UID).Include(u => u.partnar).ThenInclude(p => p.project).Include(p => p.partnar).ThenInclude(p => p.MyFinal).ThenInclude(p => p.Partnars).ToList().SingleOrDefault()!;

            try
            {
                Partnar partnar = user.partnar!;
                user.partnar!.MyFinal!.Partnars!.Add(partnar);
                user.partnar.project!.projectState = 6;
                Db.SaveChanges();
            }
            catch
            {
                return BadRequest("签到失败");
            }
            return Ok("签到成功");
        }
        [HttpGet]//获取比赛进度
        public ActionResult getProgress()
        {
            //获取token中的值
            var UID = this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value;
            User user = Db.Users.Where(u => u.StuNum.ToString() == UID).Include(u => u.partnar).ThenInclude(p => p.project).ToList().SingleOrDefault()!;
            var js = new
            {
                progressActive = user.partnar!.project!.projectState.ToString()
            };
            return new JsonResult(js);
        }
        [HttpGet]//
                 //审核阶段
        public ActionResult getExamineStage()
        {
            var UID = this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value;
            User user = Db.Users.Where(u => u.StuNum.ToString() == UID).Include(u => u.partnar).ThenInclude(p => p.project).ToList().SingleOrDefault()!;
            var js = new
            {
                isSuccess = user.partnar!.project!.isPassed.ToString()
            };
            return new JsonResult(js);
        }
        [HttpGet]//获取初赛阶段
        public ActionResult getOriginStage()
        {
            //获取token中的值
            var UID = this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value;
            User user = Db.Users.Where(u => u.StuNum.ToString() == UID).Include(p => p.partnar).ThenInclude(p => p.MyPreliminary).ThenInclude(p => p.Partnars).ToList().SingleOrDefault()!;
            if(user.partnar!.MyPreliminary!.Partnars!.Contains(user.partnar))
            {
                var js = new
                {
                    fClassroom = user.partnar!.MyPreliminary!.classRoom,
                    isSignIn = true
                };
                return new JsonResult(js);
            }
            else
            {
                var js = new
                {
                    fClassroom = user.partnar!.MyPreliminary!.classRoom,
                    isSignIn = false
                };
                return new JsonResult(js);
            }
        }
        [HttpGet]//获取决赛阶段
        public ActionResult getFinalStage()
        {
            //获取token中的值
            var UID = this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value;
            User user = Db.Users.Where(u => u.StuNum.ToString() == UID).Include(p => p.partnar).ThenInclude(p => p.MyFinal).ThenInclude(p => p.Partnars).ToList().SingleOrDefault()!;
            if (user.partnar!.MyFinal!.Partnars!.Contains(user.partnar))
            {
                var js = new
                {
                    fClassroom = user.partnar!.MyFinal!.classRoom,
                    isSignIn = true
                };
                return new JsonResult(js);
            }
            else
            {
                var js = new
                {
                    fClassroom = user.partnar!.MyFinal!.classRoom,
                    isSignIn = false
                };
                return new JsonResult(js);
            }
        }
        [HttpPost]//进入文件上传阶段
        public ActionResult enterUploadStage()
        {
            //获取token中的值
            var UID = this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value;
            User user = Db.Users.Where(u => u.StuNum.ToString() == UID).Include(u => u.partnar).ThenInclude(p => p.project).ToList().SingleOrDefault()!;
            user.partnar!.project!.projectState = 3;
            Db.SaveChanges();
            return Ok();
        }
        [HttpPost]//回到重新创建项目
        public ActionResult deleteItem()
        {
            //获取token中的值
            var UID = this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value;
            User user = Db.Users.Where(u => u.StuNum.ToString() == UID).Include(u => u.partnar).ThenInclude(p => p.project).ToList().SingleOrDefault()!;

            user.partnar!.project!.projectState = 1;//回到创建项目

            Db.SaveChanges();
            return Ok("回到创建项目");
        }
    }
}
